package com.hao.tool.web.component.interceptor;

import com.hao.tool.common.exception.ErrorException;
import com.hao.tool.common.security.JwtConstant;
import com.hao.tool.common.security.JwtSubject;
import com.hao.tool.common.security.JwtUtil;
import com.hao.tool.common.util.JsonKitUtil;
import com.hao.tool.web.common.constant.Commons;
import com.hao.tool.web.module.rbac.entity.ManagerInfo;
import com.hao.tool.web.module.rbac.service.ManagerService;
import io.jsonwebtoken.Claims;
import org.apache.catalina.connector.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by haol on 2017/3/15.
 */
@Component
public class WebLoginInterceptor extends HandlerInterceptorAdapter {

    private ManagerService managerService;

    public WebLoginInterceptor(ManagerService managerService) {
        this.managerService = managerService;
    }

    Logger logger = LoggerFactory.getLogger(WebLoginInterceptor.class);
    JwtUtil jwtUtil = new JwtUtil();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        try {
            String token = JwtUtil.getTokenValueByCookie(request, JwtConstant.COOKIE_NAME);
            if (StringUtils.isBlank(token)) {
                token = request.getHeader(JwtConstant.TOKEN_NAME);
            }
            Claims claims = JwtUtil.analyzeAndGetJWT(token);
            JwtSubject jwtSubject = JsonKitUtil.getObject(claims.getSubject(), JwtSubject.class);
            ManagerInfo dbManager = managerService.getById(jwtSubject.getId());
            if (dbManager == null) {
                throw new ErrorException("400", "当前用户不存在");
            }
            request.setAttribute(Commons.USER_NAME, dbManager.getUserName());
            // TODO: 2020-05-24 根据token的签发时间和数据库更新时间是否一致判断是否同一个用户| 根据token的值判断是否同一用户
            return true;
        } catch (NullPointerException e) {
            response.setStatus(Response.SC_FORBIDDEN);
            throw new ErrorException("400", "当前用户信息不存在，请重新登录");
        } catch (Exception e) {
            response.setStatus(Response.SC_FORBIDDEN);
            throw new ErrorException("400", e.getMessage());
        }
    }
}
